package com.zufang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zufang.entity.Message;
import com.zufang.mapper.MessageMapper;
import com.zufang.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 消息服务实现类
 */
@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    /**
     * 创建消息
     */
    @Override
    @Transactional
    public Long createMessage(Message message) {
        log.info("创建消息: userId={}, title={}", message.getUserId(), message.getTitle());
        
        // 设置初始值
        message.setRead(false);
        message.setCreateTime(LocalDateTime.now());
        message.setUpdateTime(LocalDateTime.now());
        
        // 保存消息
        save(message);
        
        log.info("创建消息成功: id={}", message.getId());
        return message.getId();
    }
    
    /**
     * 获取用户消息列表
     */
    @Override
    public Page<Message> getUserMessages(Long userId, Integer page, Integer size) {
        log.info("获取用户消息列表: userId={}, page={}, size={}", userId, page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getUserId, userId)
               .orderByDesc(Message::getCreateTime);
        
        // 执行分页查询
        Page<Message> pageParam = new Page<>(page, size);
        Page<Message> result = page(pageParam, wrapper);
        
        log.info("获取用户消息列表成功: userId={}, total={}", userId, result.getTotal());
        return result;
    }
    
    /**
     * 统计用户未读消息数量
     */
    @Override
    public int countUnreadMessages(Long userId) {
        log.info("统计用户未读消息数量: userId={}", userId);
        
        // 构建查询条件
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getUserId, userId)
               .eq(Message::getRead, false);
        
        // 执行计数查询
        long count = count(wrapper);
        
        // 确保安全转换为int
        int intCount;
        if (count > Integer.MAX_VALUE) {
            log.warn("未读消息数量超出Integer.MAX_VALUE范围: {}, 将使用最大值", count);
            intCount = Integer.MAX_VALUE;
        } else {
            intCount = (int) count;
        }
        
        log.info("统计用户未读消息数量成功: userId={}, count={}", userId, intCount);
        return intCount;
    }
    
    /**
     * 标记消息为已读
     */
    @Override
    @Transactional
    public boolean markMessageAsRead(Long messageId, Long userId) {
        log.info("标记消息为已读: messageId={}, userId={}", messageId, userId);
        
        // 验证消息是否属于当前用户
        Message message = getById(messageId);
        if (message == null) {
            log.warn("标记消息为已读失败，消息不存在: messageId={}", messageId);
            return false;
        }
        
        if (!userId.equals(message.getUserId())) {
            log.warn("标记消息为已读失败，消息不属于当前用户: messageId={}, userId={}, messageUserId={}", 
                    messageId, userId, message.getUserId());
            return false;
        }
        
        // 如果已经是已读状态，直接返回成功
        if (message.getRead()) {
            log.info("消息已经是已读状态，无需更新: messageId={}", messageId);
            return true;
        }
        
        // 更新消息为已读状态
        message.setRead(true);
        message.setUpdateTime(LocalDateTime.now());
        boolean success = updateById(message);
        
        log.info("标记消息为已读{}成功: messageId={}", success ? "" : "不", messageId);
        return success;
    }
    
    /**
     * 标记用户所有消息为已读
     */
    @Override
    @Transactional
    public boolean markAllMessagesAsRead(Long userId) {
        log.info("标记用户所有消息为已读: userId={}", userId);
        
        // 构建更新条件
        LambdaUpdateWrapper<Message> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Message::getUserId, userId)
               .eq(Message::getRead, false)
               .set(Message::getRead, true)
               .set(Message::getUpdateTime, LocalDateTime.now());
        
        // 执行批量更新
        boolean success = update(wrapper);
        
        log.info("标记用户所有消息为已读{}成功: userId={}", success ? "" : "不", userId);
        return success;
    }
    
    /**
     * 删除消息
     */
    @Override
    @Transactional
    public boolean deleteMessage(Long messageId, Long userId) {
        log.info("删除消息: messageId={}, userId={}", messageId, userId);
        
        // 验证消息是否属于当前用户
        Message message = getById(messageId);
        if (message == null) {
            log.warn("删除消息失败，消息不存在: messageId={}", messageId);
            return false;
        }
        
        if (!userId.equals(message.getUserId())) {
            log.warn("删除消息失败，消息不属于当前用户: messageId={}, userId={}, messageUserId={}", 
                    messageId, userId, message.getUserId());
            return false;
        }
        
        // 删除消息
        boolean success = removeById(messageId);
        
        log.info("删除消息{}成功: messageId={}", success ? "" : "不", messageId);
        return success;
    }

    /**
     * 发送系统消息
     */
    @Override
    @Transactional
    public boolean sendSystemMessage(Long userId, String title, String content, String type, Long relatedId) {
        log.info("发送系统消息: userId={}, title={}, type={}, relatedId={}", userId, title, type, relatedId);
        
        try {
            // 创建消息对象
            Message message = new Message();
            message.setUserId(userId);
            message.setTitle(title);
            message.setContent(content);
            message.setType(type);
            message.setReferenceId(relatedId);
            message.setRead(false);
            message.setCreateTime(LocalDateTime.now());
            message.setUpdateTime(LocalDateTime.now());
            
            // 保存消息
            boolean saved = save(message);
            
            log.info("发送系统消息{}成功: userId={}, messageId={}", saved ? "" : "不", userId, message.getId());
            return saved;
        } catch (Exception e) {
            log.error("发送系统消息异常: userId={}, error={}", userId, e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 发送普通消息
     */
    @Override
    @Transactional
    public boolean sendMessage(Long userId, String title, String content) {
        log.info("发送消息: userId={}, title={}", userId, title);
        
        try {
            // 创建消息对象
            Message message = new Message();
            message.setUserId(userId);
            message.setTitle(title);
            message.setContent(content);
            message.setType("SYSTEM"); // 默认类型为系统消息
            message.setRead(false);
            message.setCreateTime(LocalDateTime.now());
            message.setUpdateTime(LocalDateTime.now());
            
            // 保存消息
            boolean saved = save(message);
            
            log.info("发送消息{}成功: userId={}, messageId={}", saved ? "" : "不", userId, message.getId());
            return saved;
        } catch (Exception e) {
            log.error("发送消息异常: userId={}, error={}", userId, e.getMessage(), e);
            return false;
        }
    }
} 